package top.aiprogram.login.controller;

import top.aiprogram.login.Teacher;
import top.aiprogram.login.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //页面点击提交按钮后，会将表单提交到此servlet中，通过request请求获取到username 和 password，获取后调用service验证用户名密码
        //控制器中是不处理业务的
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
//        System.out.println("username: "+username+"---------"+"password: "+pwd);

        //将username和password传入LoginService中处理
        LoginService loginService = new LoginService();
        Teacher teacher =  loginService.checkLogin(username,pwd);
        StudentDao studentDao = null;
        try {
            if(teacher!=null){
                studentDao = new StudentDao();
                //如果登录成功，保存一个session
                request.getSession().setAttribute("userInfo",teacher);
                int tid = teacher.gettId();
                Student student =  studentDao.queryStudent(tid);
                //如果登录成功跳入学生列表界面
                //当一个客户端的请求到这个页面后，不做处理或者不处理完，将请求转给另一个页面处理，然后再响应给客户端。
                request.setAttribute("student",student);
                request.getRequestDispatcher("WEB-INF/view/studentList.jsp").forward(request,response);
            }else{
                request.getRequestDispatcher("login.jsp").forward(request,response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }
}
